package com.hmall.order.task;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.client.ItemClient;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/* 使用mq取消超时未支付订单*/
@Component
@Slf4j
@RequiredArgsConstructor
public class ClearOrderTask {
    private final OrderMapper orderMapper;
    private final ItemClient itemClient;
    private final OrderDetailMapper orderDetailMapper;
        @RabbitListener(bindings = @QueueBinding(
                value = @Queue("overdue.orderId.queue"),
                exchange = @Exchange(name = "hmall.delay.exchange", delayed = "true"),
                key = "hmall.overdue.order"))
        public void cancelOverdueOrder (Message message){
            String orderIds = new String(message.getBody());
            Order overdueOrder = orderMapper.selectById(orderIds);
            if (ObjectUtil.isNotNull(overdueOrder) && 1 == overdueOrder.getStatus()) {
                overdueOrder.setStatus(5);//交易关闭，取消订单
                log.info("清楚超时未支付订单，订单id：{}", orderIds);
                orderMapper.updateById(overdueOrder);
            }
            OrderDetail orderDetail = orderDetailMapper.selectById(orderIds); //超时为支付恢复库存
            if (ObjectUtil.isNotNull(orderDetail)) {
                Long itemId = orderDetail.getItemId();
                Integer num = orderDetail.getNum();
                itemClient.deductStock(itemId, -num);
                log.info("恢复商品的库存，itemId = {}，num = {}", itemId, num);
            }
        }
    }
